<?php

namespace Biz\service;

use Biz\model\ShopInviteCode as ShopInviteCodeModel;
use Biz\pockets\serviceTrait\_Async;
use Doraemon\tools\Log;
/**
 * @deprecated
 */
class ShopInviteCode
{
    use _Async;

    /**
     * 生成邀请码
     */
    public static function createInviteCode($email, $uid = '')
    {
        try {
            $code = self::createCode();
            $data = [
                "type" => $uid ? ShopInviteCodeModel::TYPE_NORMAL : ShopInviteCodeModel::TYPE_NOUID,
                "uid" => $uid,
                "code" => $code,
                "status" => ShopInviteCodeModel::STATUS_NORMAL,
                'invalid_date' => date('Y-m-d H:i:s', strtotime('+ 24 hours'))
            ];
            $result = ShopInviteCodeModel::addInviteCode($data);
            if ($result) {
                self::_async($email, $code);
            }
            return $result;
        } catch (Exception $e) {
            Log::debug("create invite code fail", ['email' => $email, 'code' => $code, 'e_msg' => $e->getMessage()]);
            throw new Exception($e->getMessage());
        }
    }

    public static function _async_createInviteCode($email, $code)
    {
        MessageSend::sendEmail($email, 'shop_invite_code', ['invite_code' => $code]);
    }

    private static function createCode($num = 8)
    {
        $element = array_merge(range(0, 9), range('A', 'Z'));
        $ticketKey = array_rand($element, $num);
        shuffle($ticketKey);
        $ticket = array();
        foreach ($ticketKey as $v) {
            $ticket[] = $element[$v];
        }
        $sn = implode('', $ticket);
        return $sn;
    }


}